import threading
import time
import json  # 添加缺失的json导入
from datetime import datetime

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from plyer import notification
import yaml
import requests
import urllib3

from service import sendemail

with open('config.yml', 'r', encoding='utf-8') as f:
    config = yaml.safe_load(f)

# 禁用SSH警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class MonitorHuiwu:
    def __init__(self, check_interval= 60*1 ):  # 添加构造函数
        self.huiwu_cookie = ''
        self.initFileRkey = ''
        self.check_interval = check_interval
        self.old_data = None
        self.stop_event = threading.Event()
        self.titles = []
        self.thread = None
        
    def send_desktop_notification(self, title, message):
        """发送桌面通知"""
        try:
            notification.notify(
                title=title,
                message=message,
                app_name="网页监控器",
                timeout=100  # 显示10秒
            )
        except Exception as e:
            print(f"发送桌面通知失败: {e}")
    
    def start_monitoring(self, huiwu_cookie, initFileRkey):  # 添加循环监控方法
        
        if self.thread is not None and self.thread.is_alive():
            self.stop_monitoring()
        
        self.huiwu_cookie = huiwu_cookie
        self.initFileRkey = initFileRkey
        
        self.stop_event.clear()
        
        # 后台执行监控线程
        self.thread = threading.Thread(target=self._run, daemon=True)
        self.thread.start()
        
    def _run(self):
        while not self.stop_event.is_set():
            self.monitorHw()
            if self.stop_event.wait(timeout=self.check_interval): 
                break  # 如果 stop_event 被 set，立即退出

    def stop_monitoring(self):  # 添加停止方法
        self.stop_event.set()
        # 等待线程完全终止（每次等待1秒）
        while self.thread.is_alive():
            self.thread.join(timeout=1.0)
    
    def monitorHw(self):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " 监控收文中......")
        
        config['huiwu_headers']['Cookie'] = self.huiwu_cookie
        try:
            url = config['huiwu_url'] + "/getJson.html?&draw=1&start=0&length=15&page=1&limit=15&action=all&_="
            response = requests.get(url + str(int(time.time() * 1000)), headers=config['huiwu_headers'], verify=False)
            response.raise_for_status()
            if response.text == '请先登录系统 !':
                print(response.text)
                return False
            new_data = json.loads(response.text)
            
            # 提取new_data中的所有rKey和FName
            new_rKeys_FNames = []
            for item in new_data['data']:
                new_rKeys_FNames.append({'rKey': item['rKey'], 'FName': item['FName'] })
            
            if self.initFileRkey != new_rKeys_FNames[0].get('rKey'):
                # print("检测到网页内容变化!")
                for item in new_rKeys_FNames:
                    if item.get('rKey') == self.initFileRkey or self.stop_event.is_set():
                        break
                    print("item-rKey：" + item.get('rKey'))
                    # 发送桌面通知
                    self.send_desktop_notification("新的来文", item.get('FName'))
                    print(item.get('FName'))
                    # 开线程发送邮件
                    threading.Thread(target=sendemail.mail, args=(item.get('FName'),), daemon=True).start()
                self.initFileRkey = new_rKeys_FNames[0].get('rKey')
            
            print("initFileRkey：" + self.initFileRkey)
        
        except requests.RequestException as e:
            print(f"获取网页内容失败: {e}")
        except json.JSONDecodeError as e:
            print(f"JSON解析失败: {e}")
            
    def setMail(self, mails):
        # 写入本地mails.txt
        with open(config['code_dir'] + '/mails.txt', 'w', encoding='utf-8') as f:
            f.write(mails)
    
    def getMails(self):
        # 从本地mails.txt读取接收人邮箱
        with open(config['code_dir'] + '/mails.txt', 'r', encoding='utf-8') as f:
            receiver_txt = f.read().strip()
        # 将字符串转为列表
        receiver_list = receiver_txt.split(',')
        return receiver_list

# if __name__ == "__main__":
#     monitor = MonitorHuiwu('sslhw_zw=HW-2; PHPSESSID=49bd21e01731017b9dcc3124803a9ee6', '6D454AA4-EB16-D87E-7BA7-5EDF04D38F5D')
#     monitor.monitorHw()